package tech.bmatch.meituan.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.bmatch.meituan.model.Merchant;
import tech.bmatch.meituan.service.MerchantService;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 实现商家初始化，保存
 */
public abstract class MerchantFileStoreServiceImpl implements MerchantService {
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static File file = new File("./data.json");
    private static final Logger logger = LoggerFactory.getLogger(MerchantFileStoreServiceImpl.class);

    @Override
    public void init() {
        if (!file.exists()) {
            return;
        }
        try {
            List<Merchant> merchantList = objectMapper.readValue(file,
                    new TypeReference<List<Merchant>>() {
                    });
            for (Merchant merchant : merchantList) {
                add(merchant);
            }
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public void store(List<Merchant> merchants) {
        if (merchants == null) {
            return;
        }
        try {
            objectMapper.writeValue(file, merchants);
        } catch (IOException e) {
            logger.error("", e);
        }
    }


    //在MerchantFileStroeServiceImpl 类的init 方法中，每次执行add 方法后都会调用store 方法执行全量保存，这个会导致重复保存，
// 如何解决这个问题呢？请尝试编写代码解决这个问题
    /*public static List<Merchant> removeDuplicateWithOrder(List<Merchant> merchants) {
        for (int i = 0; i < merchants.size() - 1; i++) {
            for (int j = merchants.size() - 1; j > i; j--) {
                if (merchants.get(j).equals(merchants.get(i))) {
                    merchants.remove(j);
                }
            }
        }
        return merchants;
    }*/
}
